<template>
  <div class="pending-tasks-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>待办任务</h2>
        <p>需要我审批的任务列表</p>
      </div>
      <div class="header-right">
        <el-badge :value="pendingTasks.length" class="task-badge">
          <el-button type="primary" @click="refreshTasks">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </el-badge>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card urgent">
        <div class="stat-icon">
          <el-icon><Warning /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ urgentTasksCount }}</div>
          <div class="stat-label">紧急任务</div>
        </div>
      </div>
      <div class="stat-card normal">
        <div class="stat-icon">
          <el-icon><Clock /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ normalTasksCount }}</div>
          <div class="stat-label">普通任务</div>
        </div>
      </div>
      <div class="stat-card overdue">
        <div class="stat-icon">
          <el-icon><Timer /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ overdueTasksCount }}</div>
          <div class="stat-label">超时任务</div>
        </div>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索任务"
        style="width: 300px; margin-right: 15px;"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-select v-model="urgencyFilter" placeholder="紧急程度" style="width: 120px; margin-right: 15px;">
        <el-option label="全部" value=""></el-option>
        <el-option label="紧急" value="紧急"></el-option>
        <el-option label="普通" value="普通"></el-option>
        <el-option label="低" value="低"></el-option>
      </el-select>
      <el-select v-model="typeFilter" placeholder="申请类型" style="width: 150px;">
        <el-option label="全部" value=""></el-option>
        <el-option label="请假申请" value="请假申请"></el-option>
        <el-option label="加班申请" value="加班申请"></el-option>
        <el-option label="报销申请" value="报销申请"></el-option>
        <el-option label="调休申请" value="调休申请"></el-option>
        <el-option label="出差申请" value="出差申请"></el-option>
        <el-option label="采购申请" value="采购申请"></el-option>
      </el-select>
    </div>

    <!-- 任务列表 -->
    <div class="tasks-table">
      <el-table :data="filteredTasks" style="width: 100%" stripe>
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="title" label="申请标题" width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="applicant" label="申请人" width="100"></el-table-column>
        <el-table-column prop="type" label="申请类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">{{ row.type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="taskName" label="当前任务" width="150" show-overflow-tooltip></el-table-column>
        <el-table-column prop="createTime" label="到达时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="urgency" label="紧急程度" width="100">
          <template #default="{ row }">
            <el-tag :type="getUrgencyTagType(row.urgency)">{{ row.urgency }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="剩余时间" width="120">
          <template #default="{ row }">
            <span :class="getRemainingTimeClass(row.deadline)">{{ getRemainingTime(row.deadline) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="approveTask(row)">审批</el-button>
            <el-button size="small" @click="viewTaskDetail(row)">详情</el-button>
            <el-button size="small" type="info" @click="delegateTask(row)">委托</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 批量操作 -->
    <div class="batch-actions">
      <el-button type="primary" @click="batchApprove">批量同意</el-button>
      <el-button type="danger" @click="batchReject">批量拒绝</el-button>
      <el-button type="info" @click="batchDelegate">批量委托</el-button>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="totalTasks"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 审批对话框 -->
    <el-dialog
      v-model="showApprovalDialog"
      title="任务审批"
      width="700px"
      :before-close="handleApprovalDialogClose"
    >
      <div v-if="currentTask" class="approval-content">
        <!-- 申请信息 -->
        <div class="application-info">
          <h4>申请信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="申请标题">{{ currentTask.title }}</el-descriptions-item>
            <el-descriptions-item label="申请人">{{ currentTask.applicant }}</el-descriptions-item>
            <el-descriptions-item label="申请类型">
              <el-tag :type="getTypeTagType(currentTask.type)">{{ currentTask.type }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="紧急程度">
              <el-tag :type="getUrgencyTagType(currentTask.urgency)">{{ currentTask.urgency }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="申请时间" :span="2">{{ formatTime(currentTask.createTime) }}</el-descriptions-item>
            <el-descriptions-item label="申请原因" :span="2">{{ currentTask.reason }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 审批表单 -->
        <div class="approval-form">
          <h4>审批意见</h4>
          <el-form :model="approvalForm" :rules="approvalRules" ref="approvalFormRef" label-width="100px">
            <el-form-item label="审批结果" prop="result">
              <el-radio-group v-model="approvalForm.result">
                <el-radio label="approved">同意</el-radio>
                <el-radio label="rejected">拒绝</el-radio>
                <el-radio label="returned">退回</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="审批意见" prop="opinion">
              <el-input
                v-model="approvalForm.opinion"
                type="textarea"
                :rows="4"
                placeholder="请输入审批意见"
              ></el-input>
            </el-form-item>
            
            <el-form-item v-if="approvalForm.result === 'approved'" label="下一审批人">
              <el-select v-model="approvalForm.nextApprover" placeholder="选择下一审批人" style="width: 100%;">
                <el-option label="张经理" value="zhang"></el-option>
                <el-option label="李总监" value="li"></el-option>
                <el-option label="王总" value="wang"></el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="抄送人员">
              <el-select v-model="approvalForm.ccUsers" multiple placeholder="选择抄送人员" style="width: 100%;">
                <el-option label="人事部" value="hr"></el-option>
                <el-option label="财务部" value="finance"></el-option>
                <el-option label="行政部" value="admin"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showApprovalDialog = false">取消</el-button>
          <el-button type="primary" @click="submitApproval">提交审批</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 委托对话框 -->
    <el-dialog
      v-model="showDelegateDialog"
      title="任务委托"
      width="500px"
    >
      <el-form :model="delegateForm" label-width="100px">
        <el-form-item label="委托给">
          <el-select v-model="delegateForm.delegateTo" placeholder="选择委托人" style="width: 100%;">
            <el-option label="张经理" value="zhang"></el-option>
            <el-option label="李主管" value="li"></el-option>
            <el-option label="王同事" value="wang"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="委托原因">
          <el-input
            v-model="delegateForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入委托原因"
          ></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDelegateDialog = false">取消</el-button>
          <el-button type="primary" @click="submitDelegate">确认委托</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Search, Clock, Warning, Timer, Document } from '@element-plus/icons-vue'

// 响应式数据
const searchKeyword = ref('')
const urgencyFilter = ref('')
const typeFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const totalTasks = ref(0)
const showApprovalDialog = ref(false)
const showDelegateDialog = ref(false)
const currentTask = ref(null)

// 表单数据
const approvalForm = ref({
  result: '',
  opinion: '',
  nextApprover: '',
  ccUsers: []
})

const delegateForm = ref({
  delegateTo: '',
  reason: ''
})

// 表单验证规则
const approvalRules = {
  result: [{ required: true, message: '请选择审批结果', trigger: 'change' }],
  opinion: [{ required: true, message: '请输入审批意见', trigger: 'blur' }]
}

// 待办任务数据
const pendingTasks = ref([
  {
    id: 1,
    title: '张三的请假申请',
    applicant: '张三',
    type: '请假申请',
    taskName: '部门经理审批',
    createTime: new Date('2024-01-16 10:30:00'),
    deadline: new Date('2024-01-18 18:00:00'),
    urgency: '普通',
    reason: '家中有事需要请假2天'
  },
  {
    id: 2,
    title: '李四的报销申请',
    applicant: '李四',
    type: '报销申请',
    taskName: '财务审批',
    createTime: new Date('2024-01-16 11:15:00'),
    deadline: new Date('2024-01-17 12:00:00'),
    urgency: '紧急',
    reason: '客户招待费用报销'
  },
  {
    id: 3,
    title: '王五的加班申请',
    applicant: '王五',
    type: '加班申请',
    taskName: '部门经理审批',
    createTime: new Date('2024-01-16 15:45:00'),
    deadline: new Date('2024-01-19 17:00:00'),
    urgency: '普通',
    reason: '项目开发需要加班'
  },
  {
    id: 4,
    title: '赵六的出差申请',
    applicant: '赵六',
    type: '出差申请',
    taskName: '总监审批',
    createTime: new Date('2024-01-15 09:20:00'),
    deadline: new Date('2024-01-16 17:00:00'),
    urgency: '紧急',
    reason: '客户现场技术支持'
  }
])

// 计算属性
const filteredTasks = computed(() => {
  let filtered = pendingTasks.value
  
  if (searchKeyword.value) {
    filtered = filtered.filter(task => 
      task.title.includes(searchKeyword.value) || 
      task.applicant.includes(searchKeyword.value) ||
      task.reason.includes(searchKeyword.value)
    )
  }
  
  if (urgencyFilter.value) {
    filtered = filtered.filter(task => task.urgency === urgencyFilter.value)
  }
  
  if (typeFilter.value) {
    filtered = filtered.filter(task => task.type === typeFilter.value)
  }
  
  return filtered
})

const urgentTasksCount = computed(() => {
  return pendingTasks.value.filter(task => task.urgency === '紧急').length
})

const normalTasksCount = computed(() => {
  return pendingTasks.value.filter(task => task.urgency === '普通').length
})

const overdueTasksCount = computed(() => {
  const now = new Date()
  return pendingTasks.value.filter(task => new Date(task.deadline) < now).length
})

// 方法
const getTypeTagType = (type) => {
  const typeMap = {
    '请假申请': 'primary',
    '加班申请': 'success',
    '报销申请': 'warning',
    '调休申请': 'info',
    '出差申请': '',
    '采购申请': 'danger'
  }
  return typeMap[type] || 'default'
}

const getUrgencyTagType = (urgency) => {
  const urgencyMap = {
    '紧急': 'danger',
    '普通': 'primary',
    '低': 'info'
  }
  return urgencyMap[urgency] || 'default'
}

const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString('zh-CN')
}

const getRemainingTime = (deadline) => {
  if (!deadline) return '无限制'
  const now = new Date()
  const deadlineDate = new Date(deadline)
  const diff = deadlineDate - now
  
  if (diff < 0) {
    return '已超时'
  }
  
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(hours / 24)
  
  if (days > 0) {
    return `${days}天${hours % 24}小时`
  } else {
    return `${hours}小时`
  }
}

const getRemainingTimeClass = (deadline) => {
  if (!deadline) return ''
  const now = new Date()
  const deadlineDate = new Date(deadline)
  const diff = deadlineDate - now
  
  if (diff < 0) {
    return 'overdue'
  } else if (diff < 24 * 60 * 60 * 1000) {
    return 'urgent'
  }
  return 'normal'
}

const refreshTasks = () => {
  ElMessage.success('任务列表已刷新')
  // 这里可以重新获取待办任务数据
}

const approveTask = (task) => {
  currentTask.value = task
  showApprovalDialog.value = true
}

const viewTaskDetail = (task) => {
  currentTask.value = task
  showApprovalDialog.value = true
}

const delegateTask = (task) => {
  currentTask.value = task
  showDelegateDialog.value = true
}

const batchApprove = () => {
  ElMessage.info('批量同意功能开发中...')
}

const batchReject = () => {
  ElMessage.info('批量拒绝功能开发中...')
}

const batchDelegate = () => {
  ElMessage.info('批量委托功能开发中...')
}

const handleSizeChange = (val) => {
  pageSize.value = val
  // 重新加载数据
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  // 重新加载数据
}

const handleApprovalDialogClose = (done) => {
  approvalForm.value = {
    result: '',
    opinion: '',
    nextApprover: '',
    ccUsers: []
  }
  done()
}

const submitApproval = () => {
  // 表单验证和提交逻辑
  ElMessage.success('审批提交成功')
  showApprovalDialog.value = false
  handleApprovalDialogClose(() => {})
  
  // 从待办列表中移除已审批的任务
  const index = pendingTasks.value.findIndex(task => task.id === currentTask.value.id)
  if (index > -1) {
    pendingTasks.value.splice(index, 1)
  }
}

const submitDelegate = () => {
  ElMessage.success('任务委托成功')
  showDelegateDialog.value = false
  delegateForm.value = {
    delegateTo: '',
    reason: ''
  }
  
  // 从待办列表中移除已委托的任务
  const index = pendingTasks.value.findIndex(task => task.id === currentTask.value.id)
  if (index > -1) {
    pendingTasks.value.splice(index, 1)
  }
}

// 生命周期
onMounted(() => {
  totalTasks.value = pendingTasks.value.length
})
</script>

<style scoped>
.pending-tasks-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left h2 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 24px;
}

.header-left p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.task-badge {
  margin-right: 10px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-card.urgent {
  border-left: 4px solid #f56c6c;
}

.stat-card.normal {
  border-left: 4px solid #409eff;
}

.stat-card.overdue {
  border-left: 4px solid #e6a23c;
}

.stat-icon {
  font-size: 32px;
  margin-right: 15px;
  color: #666;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.filter-section {
  margin-bottom: 20px;
  padding: 15px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.tasks-table {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 20px;
}

.batch-actions {
  margin-bottom: 20px;
  padding: 15px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-section {
  text-align: right;
  padding: 15px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.approval-content {
  padding: 10px 0;
}

.application-info {
  margin-bottom: 20px;
}

.application-info h4,
.approval-form h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.approval-form {
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.dialog-footer {
  text-align: right;
}

.overdue {
  color: #f56c6c;
  font-weight: bold;
}

.urgent {
  color: #e6a23c;
  font-weight: bold;
}

.normal {
  color: #409eff;
}

:deep(.el-table) {
  border-radius: 0;
}

:deep(.el-table th) {
  background-color: #f8f9fa;
  color: #333;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-button + .el-button) {
  margin-left: 8px;
}

:deep(.el-badge__content) {
  background-color: #f56c6c;
}
</style>